import React, { useEffect, useState, useRef } from "react";
import {
  getGameTime,
  setGameTimeSpeed,
  toggleGameTime,
  skipToNextTradingDay,
  type GameTimeState,
} from "../api/gameTime";

const speedOptions = [1, 2, 5, 10, 20, 50, 100, 200, 500] as const;

export const GameTimeControl: React.FC = () => {
  const [gameTime, setGameTime] = useState<GameTimeState | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const lastSyncRef = React.useRef<{ time: number; gameDate: Date; speed: number } | null>(null);

  const loadGameTime = async () => {
    try {
      const state = await getGameTime();
      const gameDate = new Date(state.gameDate);
      setGameTime(state);
      lastSyncRef.current = {
        time: Date.now(),
        gameDate: gameDate,
        speed: state.speed,
      };
      setError(null);
    } catch (e) {
      console.error(e);
      setError("无法获取游戏时间");
    }
  };

  // 从后端同步游戏时间
  useEffect(() => {
    loadGameTime();
    // 每5秒从后端同步一次，保证数据准确性
    const syncInterval = setInterval(loadGameTime, 5000);
    return () => clearInterval(syncInterval);
  }, []);

  // 格式化游戏日期
  const formatGameDate = (date: Date): string => {
    return date.toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      weekday: "short",
    });
  };

  // 在前端本地模拟时间推进（高频率更新显示）
  useEffect(() => {
    if (!gameTime || gameTime.status === "paused" || !lastSyncRef.current) {
      return;
    }

    const updateDisplay = () => {
      const sync = lastSyncRef.current;
      if (!sync) return;

      const now = Date.now();
      const realTimeDelta = now - sync.time; // 现实时间流逝（毫秒）
      
      // 根据速度计算游戏时间推进
      const gameTimeDelta = realTimeDelta * sync.speed;
      const currentGameDate = new Date(
        sync.gameDate.getTime() + gameTimeDelta
      );

      // 更新显示（不触发后端请求）
      setGameTime((prev) => {
        if (!prev || prev.status === "paused") return prev;
        return {
          ...prev,
          gameDate: currentGameDate.toISOString(),
          gameDateFormatted: formatGameDate(currentGameDate),
        };
      });
    };

    // 根据速度动态调整更新频率：速度越高，更新越频繁
    const sync = lastSyncRef.current;
    const speed = sync ? sync.speed : gameTime.speed;
    const updateInterval = Math.max(50, Math.min(500, 500 / Math.max(1, speed))); // 最快50ms，最慢500ms更新一次
    const displayInterval = setInterval(updateDisplay, updateInterval);

    return () => clearInterval(displayInterval);
  }, [gameTime?.status]);

  const handleToggle = async () => {
    setLoading(true);
    try {
      const newState = await toggleGameTime();
      const gameDate = new Date(newState.gameDate);
      setGameTime(newState);
      // 更新同步引用
      lastSyncRef.current = {
        time: Date.now(),
        gameDate: gameDate,
        speed: newState.speed,
      };
      setError(null);
    } catch (e) {
      console.error(e);
      setError("切换游戏时间状态失败");
    } finally {
      setLoading(false);
    }
  };

  const handleSpeedChange = async (speed: typeof speedOptions[number]) => {
    setLoading(true);
    try {
      const newState = await setGameTimeSpeed(speed);
      const gameDate = new Date(newState.gameDate);
      setGameTime(newState);
      // 更新同步引用
      lastSyncRef.current = {
        time: Date.now(),
        gameDate: gameDate,
        speed: newState.speed,
      };
      setError(null);
    } catch (e) {
      console.error(e);
      setError("设置时间速度失败");
    } finally {
      setLoading(false);
    }
  };

  if (!gameTime) {
    return (
      <div style={{ fontSize: 12, color: "#9ca3af" }}>加载游戏时间...</div>
    );
  }

  const cardStyle: React.CSSProperties = {
    padding: "12px 16px",
    borderRadius: "12px",
    border: "1px solid rgba(148,163,184,0.35)",
    background: "linear-gradient(135deg, rgba(15,23,42,0.96), rgba(15,23,42,0.7))",
    boxShadow: "0 8px 20px rgba(15,23,42,0.7)",
  };

  const statusColor = gameTime.status === "playing" ? "#22c55e" : "#f97316";
  const tradingStatusColor = gameTime.isTradingHours
    ? "#22c55e"
    : gameTime.isTradingDay
      ? "#fbbf24"
      : "#6b7280";

  return (
    <div style={cardStyle}>
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          marginBottom: 8,
        }}
      >
        <div style={{ fontSize: 12, fontWeight: 500, color: "#e5e7eb" }}>
          游戏时间控制
        </div>
        <div
          style={{
            fontSize: 11,
            padding: "2px 8px",
            borderRadius: 999,
            border: `1px solid ${statusColor}40`,
            backgroundColor: `${statusColor}20`,
            color: statusColor,
          }}
        >
          {gameTime.status === "playing" ? "运行中" : "已暂停"}
        </div>
      </div>

      <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>
        {gameTime.gameDateFormatted}
      </div>

      <div
        style={{
          fontSize: 11,
          color: tradingStatusColor,
          marginBottom: 12,
        }}
      >
        {gameTime.isTradingHours
          ? "交易时间"
          : gameTime.isTradingDay
            ? "非交易时间"
            : "非交易日"}
      </div>

      <div
        style={{
          display: "flex",
          gap: 8,
          alignItems: "center",
          marginBottom: 12,
          flexWrap: "wrap",
        }}
      >
        <button
          type="button"
          onClick={handleToggle}
          disabled={loading}
          style={{
            padding: "6px 12px",
            borderRadius: 6,
            border: "none",
            fontSize: 11,
            fontWeight: 500,
            cursor: loading ? "default" : "pointer",
            backgroundColor:
              gameTime.status === "playing" ? "#f97316" : "#22c55e",
            color: "#020617",
            opacity: loading ? 0.6 : 1,
            flexShrink: 0,
          }}
        >
          {gameTime.status === "playing" ? "⏸ 暂停" : "▶ 继续"}
        </button>

        <div
          style={{
            display: "flex",
            gap: 4,
            alignItems: "center",
            flex: 1,
            minWidth: 200,
          }}
        >
          <label
            style={{
              fontSize: 11,
              color: "#9ca3af",
              whiteSpace: "nowrap",
            }}
          >
            速度:
          </label>
          <select
            value={gameTime.speed}
            onChange={(e) =>
              handleSpeedChange(
                parseInt(e.target.value, 10) as typeof speedOptions[number],
              )
            }
            disabled={loading}
            style={{
              flex: 1,
              padding: "6px 8px",
              borderRadius: 6,
              border: "1px solid rgba(148,163,184,0.6)",
              backgroundColor: "#020617",
              color: "#e5e7eb",
              fontSize: 11,
              cursor: loading ? "default" : "pointer",
              opacity: loading ? 0.6 : 1,
            }}
          >
            {speedOptions.map((speed) => (
              <option key={speed} value={speed}>
                {speed}x {speed >= 100 ? "⚡" : ""}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* 快捷速度按钮 */}
      <div
        style={{
          display: "flex",
          gap: 4,
          flexWrap: "wrap",
          marginTop: 8,
        }}
      >
        {[10, 50, 100, 200, 500].map((speed) => (
          <button
            key={speed}
            type="button"
            onClick={() => handleSpeedChange(speed as typeof speedOptions[number])}
            disabled={loading || gameTime.speed === speed}
            style={{
              padding: "4px 8px",
              borderRadius: 4,
              border: `1px solid ${
                gameTime.speed === speed ? "#22c55e" : "rgba(148,163,184,0.6)"
              }`,
              backgroundColor:
                gameTime.speed === speed
                  ? "#22c55e20"
                  : "rgba(15,23,42,0.5)",
              color: gameTime.speed === speed ? "#22c55e" : "#e5e7eb",
              fontSize: 10,
              fontWeight: gameTime.speed === speed ? 600 : 400,
              cursor: loading ? "default" : "pointer",
              opacity: loading ? 0.6 : 1,
              transition: "all 0.2s",
            }}
          >
            {speed}x
          </button>
        ))}
      </div>

      {/* 非交易时间时显示跳过按钮 */}
      {!gameTime.isTradingHours && (
        <div style={{ marginTop: 12 }}>
          <button
            type="button"
            onClick={async () => {
              setLoading(true);
              try {
                const newState = await skipToNextTradingDay();
                const gameDate = new Date(newState.gameDate);
                setGameTime(newState);
                lastSyncRef.current = {
                  time: Date.now(),
                  gameDate: gameDate,
                  speed: newState.speed,
                };
                setError(null);
              } catch (e) {
                console.error(e);
                setError("跳过交易日失败");
              } finally {
                setLoading(false);
              }
            }}
            disabled={loading}
            style={{
              width: "100%",
              padding: "8px 12px",
              borderRadius: 6,
              border: "1px solid #3b82f6",
              backgroundColor: "#3b82f620",
              color: "#3b82f6",
              fontSize: 12,
              fontWeight: 500,
              cursor: loading ? "default" : "pointer",
              opacity: loading ? 0.6 : 1,
              transition: "all 0.2s",
            }}
          >
            ⏭ 跳到下一个交易日
          </button>
        </div>
      )}

      {error && (
        <div style={{ fontSize: 11, color: "#ef4444", marginTop: 4 }}>
          {error}
        </div>
      )}
    </div>
  );
};




